package com.lagou.rocketmq.service;

import com.alibaba.fastjson.JSON;
import com.lagou.rocketmq.dao.GoodDao;
import com.lagou.rocketmq.pojo.Good;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodService {

    @Resource
    private GoodDao goodDao;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @PostConstruct
    public void init() {
        List<Good> goods = goodDao.findAll();
        for (Good good : goods) {
            redisTemplate.opsForValue().set("good:" + good.getId(), good.getInventory());
        }
    }

    @Transactional
    public void placeOrder(int userId, int goodId) {
        if (!checkInventory(goodId)) {
            throw new RuntimeException("手慢了");
        }
        Map<String, Integer> param = new HashMap<>();
        param.put("userId", userId);
        param.put("goodId", goodId);
        redisTemplate.opsForValue().decrement("good:" + goodId);
        rocketMQTemplate.convertAndSend("broker-a", JSON.toJSONString(param));
    }

    public boolean checkInventory(int id) {
        int inventory = Integer.valueOf((String) redisTemplate.opsForValue().get("good:" + id));
        return inventory > 0;
    }

    @Transactional
    public int inventoryAddById(int id) {
        redisTemplate.opsForValue().increment("good:" + id);
        return goodDao.inventoryAddById(id);
    }

}
